﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;
using System.Threading;
using System.Reflection;
using UserControls;

namespace ERPForms
{
    public partial class PartenerFrm : ERPStudio.FrmCard
    {
        private Int32 IdJudetSelectat = -1;

       
        /// <summary>
        /// Daca este setata DenumireaPartener, macheta intra in adaugare cu denumirea completata
        /// </summary>
        private String _denumire = String.Empty;
        public String DenumirePartener
        {
            set
            {
                _denumire = value.ToUpper();
            }        
        }
        /// <summary>
        /// Partenerul selectat
        /// </summary>
        private Int64 _idPartsel = -1;
        public Int64 IDPartenerSelectat
        {
            set
            {
               _idPartsel = value;
            }
        }

        private StudioForm _setup = null;
        public StudioForm SetupFrm
        {
            get 
            {
                return _setup;
            }
            set
            {
                _setup = value;
            }
        }
        private Boolean ParteneriProprii = true;
        private Boolean ParteneriFolositi = false;

        public PartenerFrm(ModuleClass mInfo, Boolean partproprii, Boolean partFolositi)
            : base(mInfo)
        {
            InitializeComponent();
            Init(mInfo, partproprii);
            ParteneriFolositi = partFolositi;
        }

        private void Init(ModuleClass mInfo, Boolean partproprii)
        {
            ParteneriProprii = partproprii;


            workConnString = ModuleInfo.workConnectionString;
            ActiveControl = atributFiscalTB;
            tipPartenerSursaBindingSource.List.Add(new TipPartenerSursa("Client", "C"));
            tipPartenerSursaBindingSource.List.Add(new TipPartenerSursa("Furnizor", "F"));
            tipPartenerSursaBindingSource.List.Add(new TipPartenerSursa("Furnizor si Client", "FC"));
            esrpDataSetParteneri.Parteneri.CodUnitateColumn.DefaultValue = ModuleInfo.CodUnitate;
            esrpDataSetParteneri.Parteneri.NumeDelegatColumn.DefaultValue = String.Empty;
            esrpDataSetParteneri.Parteneri.SerieAIColumn.DefaultValue = String.Empty;
            esrpDataSetParteneri.Parteneri.NrAIColumn.DefaultValue = String.Empty;
            esrpDataSetParteneri.Parteneri.MijlocTransportColumn.DefaultValue = String.Empty;
            esrpDataSetParteneri.Parteneri.NrMijlocTransportColumn.DefaultValue = String.Empty;
            esrpDataSetParteneri.Parteneri.AtributFiscalColumn.DefaultValue = String.Empty;
            esrpDataSetParteneri.Parteneri.JudetRegComertColumn.DefaultValue = 0;
            esrpDataSetParteneri.Parteneri.NrRegComertColumn.DefaultValue = 0;
            esrpDataSetParteneri.Parteneri.AnRegComertColumn.DefaultValue = 0;
            esrpDataSetParteneri.Parteneri.TipPartenerColumn.DefaultValue = "FC";
            esrpDataSetParteneri.Parteneri.IDBancaColumn.DefaultValue = 0;
            esrpDataSetParteneri.Parteneri.AtributFiscalColumn.DefaultValue = "RO";
            esrpDataSetParteneri.Parteneri.ContBancarColumn.DefaultValue = "NEDEFINIT";
            lstPK.Add(CUIMTB);
            this.HandleRezumat += new EventHandler(PartenerFrm_HandleRezumat);
            adresaUC1.InitDB(this);
            contactUC1.InitDB(this);
            // 
            // imageList1
            // 

            this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
            this.imageList1.Images.Add(global::ERPStudio.Properties.Resources._001_54);
            this.imageList1.Images.Add(global::ERPStudio.Properties.Resources._001_20);
            this.imageList1.Images.Add(global::ERPStudio.Properties.Resources._001_55);
            this.imageList1.Images.Add(global::ERPStudio.Properties.Resources._001_57);
            this.imageList1.Images.Add(global::ERPStudio.Properties.Resources._001_06);
            this.imageList1.Images.Add(global::ERPStudio.Properties.Resources._001_40);

        }


        public PartenerFrm(ModuleClass mInfo,Boolean partproprii) : base(mInfo)
        {
            InitializeComponent();
            Init(mInfo, partproprii);
        }

        void PartenerFrm_HandleRezumat(object sender, EventArgs e)
        {
            Int32 selID = -1;
            if (parteneriBindingSource.Current != null)
            {
                ESRPDataSetParteneri.ParteneriRow prr = ((DataRowView)parteneriBindingSource.Current).Row as ESRPDataSetParteneri.ParteneriRow;
                selID =(Int32)prr.IDPartener;
            }
            ParteneriRezFrm frm = new ParteneriRezFrm(ModuleInfo, selID,ParteneriFolositi);
            frm.SelectionAddOn = true;
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if(frm.selectedDataRow!=null)
                {
                    try
                    {
                        parteneriBindingSource.RemoveFilter();
                        ESRPDataSetParteneri.ParteneriRow pr = frm.selectedDataRow.Row as ESRPDataSetParteneri.ParteneriRow;
                        parteneriBindingSource.Position = parteneriBindingSource.Find("IDPartener", pr.IDPartener);
                    }
                    catch (Exception ex)
                    {
                        TrateazaExceptie(ex);
                    }
                }
            }
        }

        override public void Cauta(object sender, EventArgs e)
        {
            ParteneriSearchFrm frm = new ParteneriSearchFrm(ModuleInfo);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                if (frm.Filtru == String.Empty)
                    return;
                parteneriBindingSource.Filter = frm.Filtru;
                /*parteneriTableAdapter.Connection = DeschideConexiune(workConnString);
                parteneriTableAdapter.FillByFiltru(ESRPDataSetParteneri.Parteneri, );
                InchideConexiune(parteneriTableAdapter.Connection);*/
                SetTitle();
            }

        }

        private String GetContPartener(SqlConnection conn,String tip)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "SELECT [Cont] FROM [ConturiSpeciale] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " AND [Tipuri] like '%"+tip+"%'";
            SqlDataReader dr = cmd.ExecuteReader();
            String filtruCont = String.Empty;
            ///nu este definit nici un cont special de tip furnizori
            ///
            if (dr == null || !dr.HasRows)
            {
                if (dr != null && !dr.IsClosed)
                    dr.Close();
                SqlCommand cmd2 = new SqlCommand("", conn);
                cmd2.CommandText = "SELECT TOP 1 [Cont] FROM [Conturi] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " AND upper(Denumire) like '"+ (tip=="FRZ"?"FURNIZOR":"CLIENT") + "%'";
                Object ret1v = cmd2.ExecuteScalar();
                String cont = "401";
                if (ret1v != null)
                    cont = ret1v.ToString();
                else
                {
                    cmd2.CommandText = "SELECT TOP 1 [Cont] FROM [Conturi] WHERE Cont <>'N/A' AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                    ret1v = cmd2.ExecuteScalar();
                    if (ret1v == null)
                    {
                        //nu exista definit planul de conturi
                        Object ret = GetSetupValue("BalconSetup", "TipUnitate", ModuleInfo.CodUnitate, conn);
                        String valStr = String.Empty;
                        if (ret == null || ret == DBNull.Value)
                        {
                            while (ret == null)
                            {
                                MessageBox.Show("Modulul Balante Contabile nu a fost configurat. \nVa rugam sa-l configurati!",
                                        "Eroare",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Hand);
                                #region Configurare Modul BalCon
                                Type mModule = null;
                                FrmCard newFrm = RuleazaFrm("erpforms", "ERPForms.BalconSetupFrm", new object[] { ModuleInfo},out mModule) as FrmCard;
                                if (newFrm == null)
                                {
                                    MyTrace("PartenerFrm:: GetContPartener(SqlConnection conn,String tip) - eroare rulare");
                                    MessageBox.Show("Eroare Program, va rugam sa va adresati distribuitorului!");
                                    return String.Empty;
                                }
                                newFrm.ShowDialog();
                                #endregion
                                ///configurare modul-----------------------------------

                                ret = GetSetupValue("BalconSetup", "TipUnitate", ModuleInfo.CodUnitate, conn);
                            }
                        }
                        valStr = ret.ToString();
                        PopuleazaConturi(valStr, conn);
                    }
                    //presupunem ca acum avem un cont de furnizori   
                    cmd2.CommandText = "SELECT TOP 1 [Cont] FROM [Conturi] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " AND upper(Denumire) like '" + (tip == "FRZ" ? "FURNIZOR" : "CLIENT") + "%'";
                    ret1v = cmd2.ExecuteScalar();
                    if (ret1v != null)
                        cont = ret1v.ToString();
                    else
                    {
                        MessageBox.Show("Plan de conturi fara cont de furnizori sau client????", "Eroare");
                        return String.Empty ;
                    }
                }
                //MessageBox.Show("Nu s-a definit nici un cont de pentru furnizori", "Eroare", MeectssageBoxButtons.OK, MessageBoxIcon.Stop);

                cmd2.CommandText = "SELECT [Tipuri] FROM [ConturiSpeciale] WHERE [CodUnitate] =" + ModuleInfo.CodUnitate.ToString() + " AND [Cont]='" + cont + "'";
                Object rTip = cmd2.ExecuteScalar();
                if(rTip == null)
                    cmd2.CommandText = "INSERT INTO [ConturiSpeciale]([Cont],[CodUnitate],[Tipuri],[Descriere]) VALUES ('" + cont + "'," + ModuleInfo.CodUnitate.ToString() +
                        ",'{"+tip+"}','Cont "+(tip=="FRZ"?"FURNIZOR":"CLIENT") + "')";
                else
                    cmd2.CommandText = "UPDATE [ConturiSpeciale] SET [Tipuri]='" + rTip.ToString() + "{" + tip + "}' WHERE [Cont]='" + cont + "' AND  [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                cmd2.ExecuteNonQuery();
            }
            else
            {
                while (dr.Read())
                {
                    if (filtruCont != String.Empty)
                        filtruCont += " OR ";
                    filtruCont += " ([Cont] like '" + dr["Cont"].ToString() + "%') ";
                }
                dr.Close();
            }
            return filtruCont;
        }

        private void PartenerFrm_Load(object sender, EventArgs e)
        {
           if (_denumire != String.Empty)
                esrpDataSetParteneri.Parteneri.DenumireColumn.DefaultValue = _denumire;

            AddBindingSource(parteneriBindingSource);
            listTableAdaptor.Add(this.parteneriTableAdapter.Adapter);

            SqlConnection conn = DeschideConexiune(workConnString);
            Object ret = GetSetupValue("FaresSetup", "ParteneriProprii", ModuleInfo.CodUnitate, conn);

            if (ret == null || ret == DBNull.Value)
            {
                while (ret == null)
                {
                    MessageBox.Show("Modulul Parteneri nu a fost configurat. \nVa rugam sa-l configurati!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                    if (_setup != null)
                    {
                        _setup.ShowDialog();
                        ret = GetSetupValue("FaresSetup", "ParteneriProprii", ModuleInfo.CodUnitate, conn);
                    }
                    else
                        break;
                }
            }
            ParteneriProprii = Convert.ToBoolean(ret);
           


            this.conturiTableAdapter.Connection = conn;
            SqlDataAdapter sqlDA = new SqlDataAdapter(new SqlCommand("SELECT Cont, CodUnitate, Denumire, Tip, Terminal, ContParinte, EsteAnalitic, DebitInitial, CreditInitial, DebitPrecedent, CreditPrecedent, Categorie, RulajDebit, RulajCredit, Sold, SortValue FROM dbo.Conturi" +
                " WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " AND  [Terminal]=1 ", conn));
            /*if (filtruCont != String.Empty)
                sqlDA.SelectCommand.CommandText += " AND (" + filtruCont + ")";*/
           
            sqlDA.SelectCommand.Connection = conn;
            sqlDA.Fill(this.esrpDataSetParteneri.Conturi);

            if (conturiBindingSource.Count > 0)
            {
                conturiBindingSource.MoveFirst();
                esrpDataSetParteneri.Parteneri.ContColumn.DefaultValue = ((DataRowView)conturiBindingSource.Current).Row["Cont"].ToString();
            }

            conturiBindingSource.Filter = GetContPartener(conn, "FRZ");
            conturiBindingSource.Sort = "SortValue";

            conturiBindingSourceClient.Filter = GetContPartener(conn, "CLT");
            conturiBindingSourceClient.Sort = "SortValue";

            //this.conturiTableAdapter.FillByCont(this.ESRPDataSetParteneri.Conturi,CodUnitate,filtruCont);
            this.mijloaceTransportTableAdapter.Connection = conn;
            this.mijloaceTransportTableAdapter.Fill(this.esrpDataSetParteneri.MijloaceTransport);
			this.localitatiTableAdapter.Connection = conn;
			this.localitatiTableAdapter.Fill(this.esrpDataSetParteneri.Localitati);
			this.judeteTableAdapter.Connection = conn;
			this.judeteTableAdapter.Fill(this.esrpDataSetParteneri.Judete);
            this.tariTableAdapter.Connection = conn;
            this.tariTableAdapter.Fill(this.esrpDataSetParteneri.Tari);

            this.contactTableAdapter.Connection = conn;
            this.contactTableAdapter.Fill(this.esrpDataSetParteneri.Contact);

            this.parteneriTableAdapter.Connection = conn;
           
            this.banciTableAdapter.Connection = conn;
            this.banciTableAdapter.Fill(this.esrpDataSetParteneri.Banci);
           
            
            if (!ParteneriFolositi)
            {
                if (ParteneriProprii)
                    this.parteneriTableAdapter.FillByUnitate(esrpDataSetParteneri.Parteneri, ModuleInfo.CodUnitate);
                else
                    this.parteneriTableAdapter.Fill(esrpDataSetParteneri.Parteneri);
            }
            else
                this.parteneriTableAdapter.FillByParteneriFolositi(esrpDataSetParteneri.Parteneri, ModuleInfo.CodUnitate, ParteneriFolositi);

            ret = GetSetupValue("Unitati", "IDJudet", ModuleInfo.CodUnitate, conn);
            SqlCommand cmd = new SqlCommand("", conn);
            Object retu = null;
            if (ret != null && ret != DBNull.Value)
            {
                esrpDataSetParteneri.Parteneri.IDJudetColumn.DefaultValue = Convert.ToInt32(ret);
                cmd.CommandText = "SELECT IDTara FROM Judete WHERE IDJudet = " + ret.ToString();
                retu = cmd.ExecuteScalar();

                if (retu != null && retu != DBNull.Value)
                {
                    esrpDataSetParteneri.Parteneri.IDTaraColumn.DefaultValue = Convert.ToInt32(retu);
                }
            }
            else
            {
                ///nu a fost setat partenerul 
                ///atunci cautam cel mai frecvent judet la partenerii asignati
                ///
                if (parteneriBindingSource.Count != 0)
                {
                    cmd.CommandText = "(SELECT Max(IDLocalitate) FROM  (SELECT TOP 1 IDLocalitate,COUNT(*) c FROM Parteneri WHERE IDLocalitate<>0" +
                        (ParteneriProprii ? " AND CodUnitate=" + ModuleInfo.CodUnitate.ToString() : "")
                        + " GROUP BY IDLocalitate ORDER BY c desc) cc)";
                    cmd.CommandType = CommandType.Text;
                    retu = cmd.ExecuteScalar();
                    if (retu != null && retu != DBNull.Value)
                    {
                        esrpDataSetParteneri.Parteneri.IDLocalitateColumn.DefaultValue = Convert.ToInt32(retu);

                        ///selectam si tara corespunzatoare judetului
                        ///
                        cmd.CommandText = "SELECT IDJudet FROM Localitati WHERE IDLocalitate = " + retu.ToString();
                        retu = cmd.ExecuteScalar();
                        if (retu != null && retu != DBNull.Value)
                        {
                            esrpDataSetParteneri.Parteneri.IDJudetColumn.DefaultValue = Convert.ToInt32(retu);
                            cmd.CommandText = "SELECT IDTara FROM Judete WHERE IDJudet = " + retu.ToString();
                            retu = cmd.ExecuteScalar();

                            if (retu != null && retu != DBNull.Value)
                            {
                                esrpDataSetParteneri.Parteneri.IDTaraColumn.DefaultValue = Convert.ToInt32(retu);
                            }

                        }
                    }

                }
                else
                {
                    cmd.CommandText = "SELECT MAX(IDJudet) FROM Localitati";
                    retu = cmd.ExecuteScalar();
                    if (retu != null && retu != DBNull.Value)
                    {
                        esrpDataSetParteneri.Parteneri.IDJudetColumn.DefaultValue = Convert.ToInt32(retu);
                        cmd.CommandText = "SELECT IDTara FROM Judete WHERE IDJudet = " + retu.ToString();
                        retu = cmd.ExecuteScalar();

                        if (retu != null && retu != DBNull.Value)
                        {
                            esrpDataSetParteneri.Parteneri.IDTaraColumn.DefaultValue = Convert.ToInt32(retu);
                        }

                    }
                
                }

            }

            InchideConexiune(conn);


            AddButton("Salveaza", global::ERPStudio.Properties.Resources.salvare, Salvare, ToolStripItemAlignment.Right, true);
            AddButton("Verifica", global::ERPStudio.Properties.Resources._001_18, Verifica, ToolStripItemAlignment.Right, false);
            AddButton("Conturi Bancare", global::ERPStudio.Properties.Resources.wallet, Conturi_Bancare, ToolStripItemAlignment.Right, false);
            /// functia care se apeleaza in momentul in care se apasa F9
            /// 

            HandleSalvare += new EventHandler(Salvare);
            if (parteneriBindingSource.Count == 0 || _denumire!=String.Empty)
                Adauga(this, null);
            else
                if (_idPartsel != -1)
                {
                    int pos =parteneriBindingSource.Find("IDPartener", _idPartsel);
                    parteneriBindingSource.Position = pos;
                }
            if (ParteneriFolositi)
            {
                MessageBoxFrm mbt = new MessageBoxFrm("Atentionare", "Se afiseaza doar pastenerii folositi in ordonantare!\n Daca doriti modificarea acestei setari intrati in Parametrizare Modul ExBug si debifati \"Afiseaza partenerii folositi\"!", String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, null);
                mbt.AddButton("Ok", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();
            }
            
        }

        #region Verifica finante

        public static string MESAJ_EROARE = null;
        static bool first = true;

        private void Verifica(object sender, EventArgs e)
        {
            if (CUIMTB.Text.Trim() == String.Empty)
            {
                MessageBox.Show("Va rugam introduceti codul fiscal pe care doriti sa-l verificati!", "Eroare",
                   MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            //PostRequest("http://apt1.mfinante.ro/site/contribuabili/link.jsp?body=/cod.do", "cod", CUIMTB.Text);
            //PostRequest("http://voes.mfinante.ro/codfiscal/agenticod.html", "cod", CUIMTB.Text);
            webBrowser1.DocumentCompleted -= new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
            webBrowser1.DocumentCompleted -= new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted_vid);
            webBrowser1.DocumentCompleted+=new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted_login);
            first = true;
            try
            {
                webBrowser1.Navigate(new Uri("http://voes.mfinante.ro/codfiscal/pjuridice.html"));
            }
            catch (ObjectDisposedException ode)
            {
                MESAJ_EROARE = ode.Message;
            }
            catch (InvalidOperationException ioe)
            {
                MESAJ_EROARE = ioe.Message;
            }
            catch (ArgumentException ae)
            {
                MESAJ_EROARE = ae.Message;
            }
        }

        public void NaviGate()
        {
            webBrowser1.Navigate(new Uri("http://voes.mfinante.ro/codfiscal/agenticod.html?cap=105421439"));
        }

        private void webBrowser1_DocumentCompleted_login(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (first)
            {
                first = false;
                NaviGate();
            }
            else
            {
                webBrowser1.DocumentCompleted -= new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted_login);
                webBrowser1.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
                webBrowser1.Document.Forms[0].All["cod"].SetAttribute("value", CUIMTB.Text);
                webBrowser1.Document.GetElementById("B1").Focus();
                webBrowser1.Document.GetElementById("B1").InvokeMember("click");
            }

        }

        private void PostRequest(String URL, String Names, String Values)
        {
            String FormData = String.Empty;
            String Name = String.Empty, Value = String.Empty;

            //Enumerate form names And it's values
            //and built string representaion of the form data

            Name = URLEncode(Names);
            Value = URLEncode(Values);
            if (FormData != String.Empty)
                FormData = FormData + "&";
            FormData = FormData + Name + "=" + Value;

            //Post the data To the destination URL

            IEPostStringRequest(URL, FormData);
        }

        private String URLEncode(String Data)
        {
            Char c;
            String Out = String.Empty;

            for (Int16 I = 0; I < Data.Length; I++)
            {
                //c = Asc(Mid(Data, I, 1))
                c = Data[I];
                if (c == 32)
                    Out = Out + "+";
                else
                    if (c < 48)
                        Out = Out + "%" + String.Format("{0:X}", c);
                    else
                        Out = Out + c.ToString();
            }
            return Out;
        }

        private void IEPostStringRequest(String URL, String FormData)
        {
            //Send the form data To URL As POST request

            //ReDim bFormData(Len(FormData) - 1)
            Encoding a = System.Text.Encoding.UTF8;
            Byte[] bFormData = a.GetBytes(FormData);
            //bFormData = StrConv(FormData, vbFromUnicode)

            webBrowser1.Navigate(URL, "_self", bFormData, "Content-Type: application/x-www-form-urlencoded\r\n");
            Cursor.Current = Cursors.WaitCursor;
        }

        private void webBrowser1_DocumentCompleted_vid(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            webBrowser1.DocumentCompleted -= new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
            webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted_vid);

            Cursor.Current = Cursors.Default;
            String[] dateFin = new String[20];
            String rd = String.Empty;
            int careUrmeaza = -1;
            if (webBrowser1.Document != null)
            {
                HtmlDocument hDoc = webBrowser1.Document;
                HtmlElementCollection elems = hDoc.GetElementsByTagName("TD");
                foreach (HtmlElement elem in elems)
                {
                    if (elem.OuterText == null || elem.OuterText.Contains("AGENTUL ECONOMIC"))
                        continue;
                    if (careUrmeaza == -1)
                    {

                        if (elem.OuterText.ToLower().Contains("denumire platitor:"))
                            careUrmeaza = 0;
                        else
                            if (elem.OuterText.ToLower().Contains("adresa:"))
                                careUrmeaza = 1;
                            else
                                if (elem.OuterText.ToLower().Contains("judetul:"))
                                    careUrmeaza = 3;
                                else
                                    if (elem.OuterText.ToLower().Contains("registrul comertului:"))
                                        careUrmeaza = 4;
                                    else
                                        if (elem.OuterText.ToLower().Contains("codul postal:"))
                                            careUrmeaza = 5;
                                        else
                                            if (elem.OuterText.ToLower().Contains("telefon:"))
                                                careUrmeaza = 6;
                                            else
                                                if (elem.OuterText.ToLower().Contains("fax"))
                                                    careUrmeaza = 7;
                                                else
                                                {
                                                    careUrmeaza = -1;
                                                    continue;
                                                }
                        rd += elem.OuterText;
                    }
                    else
                    {
                        if (careUrmeaza == 1)
                        {
                            String[] adr = elem.OuterText.Split(' ');
                            Boolean localitate = false;
                            for (Int16 i = 0; i < adr.Length; i++)
                            {
                                Char[] cifre = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
                                if (!localitate)
                                {
                                    if (dateFin[careUrmeaza] != String.Empty)
                                        dateFin[careUrmeaza] += " ";
                                    dateFin[careUrmeaza] += adr[i];

                                }
                                else
                                {
                                    if (dateFin[careUrmeaza + 1] != String.Empty)
                                        dateFin[careUrmeaza + 1] += " ";
                                    dateFin[careUrmeaza + 1] += adr[i];
                                }
                                if (adr[i].IndexOfAny(cifre) >= 0)
                                    localitate = true;
                            }
                            rd += "Strada: " + dateFin[careUrmeaza] + "\r\n";
                            rd += "Localitatea: " + dateFin[careUrmeaza + 1] + "\r\n";
                        }
                        else
                        {
                            dateFin[careUrmeaza] = elem.OuterText;
                            rd += elem.OuterText + "\r\n";
                        }
                        careUrmeaza = -1;
                    }
                }
                if (rd.Trim() == String.Empty)
                {
                    MessageBox.Show("Nu exista informatii despre acest agent economic!", "Verificare Ministerul finantelor", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (MessageBox.Show(rd, "Verificare Ministerul finantelor", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (dateFin[0] != null)
                        denumireTB.Text = dateFin[0].Trim();
                    int idseljud = 0;
                    if (dateFin[3] != null)
                    {
                        string unicodeString = dateFin[3].Trim().ToUpper();

                        // Create two different encodings.
                        Encoding ascii = Encoding.ASCII;
                        Encoding unicode = Encoding.Unicode;

                        // Convert the string into a byte[].
                        byte[] unicodeBytes = unicode.GetBytes(unicodeString);

                        // Perform the conversion from one encoding to the other.
                        byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);

                        // Convert the new byte[] into a char[] and then into a string.
                        // This is a slightly different approach to converting to illustrate
                        // the use of GetCharCount/GetChars.
                        char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
                        ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
                        string asciiString = new string(asciiChars);
                        asciiString = asciiString.Replace("?", "");

                        int idx = JudetCB.FindString(asciiString);
                        if (idx >= 0)
                        {
                            JudetCB.SelectedIndex = idx;
                            idseljud = Convert.ToInt32(JudetCB.SelectedValue);
                        }

                    }
                    if (dateFin[2] != null)
                    {
                        string unicodeString = dateFin[2].Trim().ToUpper();
                        // Create two different encodings.
                        Encoding ascii = Encoding.ASCII;
                        Encoding unicode = Encoding.Unicode;

                        // Convert the string into a byte[].
                        byte[] unicodeBytes = unicode.GetBytes(unicodeString);

                        // Perform the conversion from one encoding to the other.
                        byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);

                        // Convert the new byte[] into a char[] and then into a string.
                        // This is a slightly different approach to converting to illustrate
                        // the use of GetCharCount/GetChars.
                        char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
                        ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
                        string asciiString = new string(asciiChars);
                        asciiString = asciiString.Replace("?", "");
                        asciiString = asciiString.Replace("MUNICIPIUL", "").Trim();
                        //iDLocalitateCB.Text = dateFin[2].Trim().ToUpper();
                        int idxl = iDLocalitateCB.FindString(asciiString);
                        if (idxl >= 0)
                        {
                            iDLocalitateCB.SelectedIndex = idxl;

                        }
                        else
                        {
                            SqlCommand cmd = new SqlCommand("fares_ExistaLocalitate", DeschideConexiune(workConnString));
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.Add(new SqlParameter("@nume", dateFin[2].Trim().ToUpper()));
                            cmd.Parameters.Add(new SqlParameter("@idjudet", idseljud));
                            cmd.Parameters.Add(new SqlParameter("@idloc", 0));
                            cmd.Parameters[2].Direction = ParameterDirection.Output;
                            cmd.Parameters[2].DbType = DbType.Int32;
                            cmd.Parameters[2].IsNullable = false;
                            cmd.ExecuteScalar();

                            localitatiTableAdapter.Connection = cmd.Connection;
                            localitatiTableAdapter.Fill(esrpDataSetParteneri.Localitati);
                            localitatiBindingSource.ResetBindings(false);
                            InchideConexiune(cmd.Connection);
                            iDLocalitateCB.SelectedValue = cmd.Parameters[2].Value;
                        }

                    }
                    if (dateFin[1] != null)
                        stradaTB.Text = dateFin[1].Trim();
                    if (dateFin[6] != null)
                        telefonTB.Text = dateFin[6].Trim();
                    if (dateFin[7] != null)
                        faxTB.Text = dateFin[7].Trim();
                    if (dateFin[4] != null)
                    {
                        String[] reg = dateFin[4].Split('/');
                        if (reg.Length >= 3)
                        {
                            judetRegComertNUD.Text = reg[0].Replace("J", string.Empty);
                            nrRegComertNUD.Value = Convert.ToDecimal(reg[1]);
                            anulRegComerNUD.Value = Convert.ToDecimal(reg[2]);
                        }
                    }
                    if (dateFin[5] != null)
                        codPostalTB.Text = dateFin[5].Trim();
                    //verificare exixtenta judet
                    //iDJudetComboBox_Validating(iDJudetCB,null);
                    //iDLocalitateComboBox_Validating(iDLocalitateCB, null);
                }
            }
            else
            {
                MessageBox.Show("Nu exista informatii despre acest agent economic!", "Verificare Ministerul finantelor", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            }
            Application.DoEvents();
        }
        #endregion

        private void PopuleazaConturi(String TipUnitate, SqlConnection con)
        {
            #region Adaugare cont N/A
            ///verifica existenta contului radacina pentru unitatea curenta
            ///
            SqlCommand cmd = new SqlCommand("SELECT Count(*) FROM [Conturi] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate + " AND [Cont]='N/A'",
                    con);
            Object ret = cmd.ExecuteScalar();
            if (ret != null && Convert.ToInt32(ret) == 0)
            {
                cmd.CommandText = "INSERT INTO [Conturi]([Cont],[CodUnitate],[Denumire],[Tip],[Terminal],[ContParinte],[EsteAnalitic],[Categorie]) VALUES ('N/A'," + ModuleInfo.CodUnitate.ToString() + ",'Principal','B',0,'N/A',1,0)";
                cmd.ExecuteNonQuery();
            }
            #endregion
            cmd.CommandText = "INSERT INTO [Conturi]([Cont],[Denumire],[Tip],[Terminal],[ContParinte],[EsteAnalitic],[Categorie],[CodUnitate],[DebitInitial],[CreditInitial],[DebitPrecedent],[CreditPrecedent],[RulajDebit] ,[RulajCredit])" +
                "SELECT  [Cont],[Denumire],[Tip],[Terminal],[ContParinte],0,[Categorie]," + ModuleInfo.CodUnitate.ToString() + ",0,0,0,0,0,0 FROM [PlanConturi] pl WHERE [TipUnitate]='" + TipUnitate + "' AND  [Preluare] = 1 "+
                " AND [ContParinte] in (SELECT [CONT] FROM [Conturi] where [CodUnitate]="+ModuleInfo.CodUnitate.ToString() +
                ") AND pl.[Cont] NOT IN (SELECT [CONT] FROM [Conturi] where [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() +
                ")";
            int caterec = 1;
            while(caterec!=0)
            {
                try
                {
                    caterec = cmd.ExecuteNonQuery();
                }
                catch(SqlException ex)
                {
                MessageBox.Show(ex.ToString());
                }
            }
        }

        private Boolean ValideazaCIF(String cif)
        {
            cif = cif.Trim();
            if (cif == String.Empty)
                return true;
            if (cif.Length == 13)
                return true;
            Int16[] Cheie = {2,3,5,7,1,2,3,5,7};
            Int16 suma=0, i=0;
            Int16 ultimaCifra = Convert.ToInt16(Convert.ToInt16(cif[cif.Length - 1])-Convert.ToInt16('0'));
           
            String cifr = cif.Substring(0, cif.Length - 1),cifr2=String.Empty;
            foreach (Char c in cifr)
                cifr2 = c.ToString() + cifr2;


            foreach (Char c in cifr2)
            {
                suma += Convert.ToInt16(Cheie[i] * (Convert.ToInt16(c) - Convert.ToInt16('0')));
                i++;
                if (i >= 9) break;
            }

            return (suma*10)%11 == ultimaCifra;
        }

       
        private void Conturi_Bancare(object sender, EventArgs e)
        {
            if(parteneriBindingSource.Current==null)
                return;
            ESRPDataSetParteneri.ParteneriRow rdP = ((DataRowView)parteneriBindingSource.Current).Row as
                 ESRPDataSetParteneri.ParteneriRow;
            ConturiBancareParteneriFrm frm = new ConturiBancareParteneriFrm(ModuleInfo,rdP.IDPartener,rdP.ContBancar,rdP.IDBanca);
            frm.ShowDialog();
            int pozCur = parteneriBindingSource.Position;
            this.parteneriTableAdapter.Connection = DeschideConexiune(workConnString);
            this.parteneriTableAdapter.Fill(this.esrpDataSetParteneri.Parteneri);
            InchideConexiune(this.parteneriTableAdapter.Connection);
            parteneriBindingSource.Position = pozCur;
        }

        private void CUIMTB_Validating(object sender, CancelEventArgs e)
        {
            if (CUIMTB.Text == val_initiala_CUI)
                return;
            if (!ValideazaCIF(CUIMTB.Text))
            {
                if (MessageBox.Show("Cod CIF incorect(cifra de control este incorecta)!\nDoriti utilizarea lui?", "Eroare", MessageBoxButtons.YesNo, MessageBoxIcon.Stop) != DialogResult.Yes)
                {
                    e.Cancel = true;
                    return;
                }
            }
            if (CUIMTB.Text.Trim() == String.Empty)
            {
                if (MessageBox.Show("Va rugam completati codul unic de identificare!", "Eroare", MessageBoxButtons.YesNo, MessageBoxIcon.Stop) == DialogResult.Yes)
                    return;
                e.Cancel = true;
            }
            /// CUI - unic
            /// 
            Decimal rez = Decimal.Zero;
            Decimal.TryParse(CUIMTB.Text, out rez);
            if (rez == Decimal.Zero)
            {
                MessageBox.Show("Va rugam completati codul unic de identificare cu o valoare corecta!", "Eroare", MessageBoxButtons.YesNo, MessageBoxIcon.Stop);
                e.Cancel = true;
                return;
            }
            SqlCommand cmd = new SqlCommand("SELECT [IDPartener] FROM Parteneri WHERE CUI=" + CUIMTB.Text, DeschideConexiune(workConnString));
            if (ParteneriProprii)
                cmd.CommandText += " AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object ret = cmd.ExecuteScalar();
            if (ret != null && ret != DBNull.Value)
            {
                
                if (parteneriBindingSource.Current != null)
                {
                    ESRPDataSetParteneri.ParteneriRow drr = ((DataRowView)parteneriBindingSource.Current).Row as ESRPDataSetParteneri.ParteneriRow;
                    String den = CUIMTB.Text;
                    if (drr.IDPartener!=Convert.ToInt32(ret))
                    {
                        parteneriBindingSource.CancelEdit();
                        parteneriBindingSource.Sort = "CUI";
                        parteneriBindingSource.Position = parteneriBindingSource.Find("CUI", den);
                        parteneriBindingSource.ResetCurrentItem();
                        SetTitle();
                        MessageBox.Show("CUI-ul introdus:" + CUIMTB.Text + " se regaseste in baza de date la partenerul afisat pe ecran.", "Avertisment", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    }
                                            
                }
                
            }
            InchideConexiune(cmd.Connection);
            val_initiala_CUI = CUIMTB.Text; 
        }

        private void iDLocalitateComboBox_Validating(object sender, CancelEventArgs e)
        {
            if(iDLocalitateCB.Text.Trim()==String.Empty)
                return;

            if (JudetCB.SelectedIndex == -1)
            {
                MessageBox.Show("Va rugam sa selectati judetul inainte de a selecta localitatea!","Stop");
                if (e != null)
                    e.Cancel = true;
                return;
            }
            String locInsert = iDLocalitateCB.Text.Trim();
            int nrLoc = localitatiBindingSource.Count;
            iDLocalitateCB.Text = locInsert;
            if (nrLoc == 0 || iDLocalitateCB.SelectedIndex==-1)
            {
                LocalitatiFrm frm = new LocalitatiFrm(ModuleInfo);
                frm.CodJudet = Convert.ToInt32(JudetCB.SelectedValue);
                frm.LocalitateAdaugate = locInsert;
                frm.ShowDialog();

                SqlConnection con = DeschideConexiune(workConnString);
                localitatiTableAdapter.Connection = con;
                localitatiTableAdapter.Fill(esrpDataSetParteneri.Localitati);
                InchideConexiune(con);

                if(e!=null)
                    e.Cancel = true;

            }
        }

        private void iDJudetComboBox_Validating(object sender, CancelEventArgs e)
        {
            SqlConnection con = null;
            if (JudetCB.Text.Trim() == String.Empty)
                return;
            String SalvareJudete = JudetCB.Text;
            while(JudetCB.SelectedIndex == -1)
            {
                ///nu s-a incarcat nici un judet pentru ca nu s-a selectat nici o tara - 
                ///le incarcam pe toate
                JudeteFrm frm = new JudeteFrm(ModuleInfo, (TariCB.SelectedIndex == -1)?-1:Convert.ToInt32(TariCB.SelectedValue), JudetCB.Text);
                frm.ShowDialog();

                con = DeschideConexiune(workConnString);
                judeteTableAdapter.Connection = con;
                judeteTableAdapter.Fill(esrpDataSetParteneri.Judete);
                InchideConexiune(con);
                JudetCB.Text = SalvareJudete;
            }

            if (TariCB.SelectedIndex == -1)
            {
                if (e != null)
                    e.Cancel = true;
                MessageBox.Show("Va rugam selectati o tara din lista inainte de a selecta judetul!", "Atentie", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                TariCB.Focus();
                return;
            }


        }

       

        private void ExistaLocalitate(String nume)
        { 
            
        }

        private void NUD_Enter(object sender, EventArgs e)
        {
            NumericUpDown nud = sender as NumericUpDown;
            nud.Select(0, nud.Value.ToString().Length);
        }

        private void contCB_Validating(object sender, CancelEventArgs e)
        {

            ComboBox cb = sender as ComboBox;
            if (cb == null || (parteneriBindingSource.Current == null))
                return;
            String denumire = cb.Text.Trim(), den = String.Empty;
            if (denumire == String.Empty)
                return;

            String contFurn = contCB.Text;
            String contCli = contClientCB.Text;
            if (cb.SelectedIndex == -1)
            {
                ///daca nu ezista in lista de selectie
                ///
                using (SqlConnection con = DeschideConexiune(workConnString))
                {
                    SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM [Conturi] WHERE [Cont]='" + denumire + "' AND [CodUnitate]="+ ModuleInfo.CodUnitate.ToString(), con);
                    Object ret = cmd.ExecuteScalar();
                    ESRPDataSetParteneri.ParteneriRow rp = ((DataRowView)parteneriBindingSource.Current).Row as ESRPDataSetParteneri.ParteneriRow;
                    //daca nu exista in baza de date contul introdus
                    if (Convert.ToInt16(ret) == 0)
                    {
                        Type mModule = null;
                        FrmCard newFrm = RuleazaFrm("erpforms", "ERPForms.ContCardFrm", new object[] { ModuleInfo, true }, out mModule) as FrmCard;
                        if (newFrm == null)
                        {
                            MyTrace("PartenerFrm::contCB_Validating(object sender, CancelEventArgs e) - eroare rulare");
                            MessageBox.Show("Eroare Program, va rugam sa va adresati distribuitorului!");
                            return;
                        }

                        

                        mModule.InvokeMember("contAdaugat", BindingFlags.SetProperty, null, newFrm, new object[] { denumire });
                        mModule.InvokeMember("denCont", BindingFlags.SetProperty, null, newFrm, new object[] { rp.Denumire });


                        if (newFrm.ShowDialog() == DialogResult.Cancel || newFrm.currentRow == null)
                        {
                            e.Cancel = true;
                            return;
                        }

                        denumire = newFrm.currentRow.Row["cont"].ToString().ToUpper();
                        //den = newFrm.currentRow.Row["Denumire"].ToString();

                        if (newFrm.NoRecAdded > 0)
                        {
                            conturiTableAdapter.Connection = DeschideConexiune(workConnString);
                            conturiTableAdapter.FillByCodUnitate(esrpDataSetParteneri.Conturi, ModuleInfo.CodUnitate);
                            InchideConexiune(conturiTableAdapter.Connection);
                        }

                        
                        
                    }
                    //il adaugam in lista de conturi
                    //verificam daca Exista in 
                    cmd.CommandText = "SELECT [Tipuri] FROM [ConturiSpeciale] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " AND [Cont]='" +
                        denumire + "'";
                    Object rez = cmd.ExecuteScalar();
                    if (rez != null && rez != DBNull.Value)
                    {
                        //exista contul
                        cmd.CommandText = "UPDATE [ConturiSpeciale] SET [Tipuri]='" + rez + (cb.Name == "contClientCB" ? "{CLT}" : "{FRZ}") + "' WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " AND [Cont]='" +
                            denumire + "'";
                    }
                    else
                    {
                        cmd.CommandText = "INSERT INTO [ConturiSpeciale]([Cont],[CodUnitate],[Tipuri],[Descriere]) VALUES ('" + denumire + "'," + ModuleInfo.CodUnitate.ToString() +
                            ",'" + (cb.Name == "contClientCB" ? "{CLT}" : "{FRZ}") + "','')";
                    }
                    cmd.ExecuteScalar();
                    //String cntSave = cb.Text;
                    if (cb == contCB)
                        conturiBindingSource.Filter = GetContPartener(con, "FRZ");
                    if (cb == contClientCB)
                        conturiBindingSourceClient.Filter = GetContPartener(con, "CLT");
                    //cb.Text = cntSave;
                }
                
            }
            //incarca 
         
            //denContCB.Text = den;
            if (contFurn != String.Empty)
            {
                conturiBindingSource.Position = conturiBindingSource.Find("Cont", contFurn);
            }
            else
            {
                contCB.SelectedIndex = -1;
                denContCB.SelectedIndex = -1;
            }
            if (contCli != String.Empty)
            {
                conturiBindingSourceClient.Position = conturiBindingSourceClient.Find("Cont", contCli);
            }
            else
            {
                contClientCB.SelectedIndex = -1;
                denContClientCB.SelectedIndex = -1;
            }
           
         
        }

        private void denumireTB_Validating(object sender, CancelEventArgs e)
        {
            TextBox tb = sender as TextBox;
            if(tb!=null)
                tb.Text = tb.Text.Trim();
        }

        private String val_initiala_CUI = String.Empty;
        private void CUIMTB_Enter(object sender, EventArgs e)
        {
            val_initiala_CUI = CUIMTB.Text;
        }

        private void tabControlPrincipal_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControlPrincipal.SelectedTab == adreseTP)
            {
                
            }
        }

        private void tabControlPrincipal_Selecting(object sender, TabControlCancelEventArgs e)
        {
            ///setul curent este partenerii
            SetCurrentDataSource(parteneriBindingSource);
            if (tabControlPrincipal.SelectedTab == adreseTP || tabControlPrincipal.SelectedTab == contacteTP)
            {
                DataRowView dr = ((DataRowView)parteneriBindingSource.Current);
                if ((dr != null) && dr.IsNew)
                {
                    e.Cancel = true;
                    MessageBox.Show("Va rugam sa finalizati adaugarea partenerului inainte de a trece la celelalte sectiuni ale machetei!\n",
                        "Stop",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Stop);
                    return;
                }

                ESRPDataSetParteneri.ParteneriRow dr2 = ((DataRowView)parteneriBindingSource.Current).Row as ESRPDataSetParteneri.ParteneriRow;
                adresaUC1.parentForm = this;
                contactUC1.parentForm = this;
                if (tabControlPrincipal.SelectedTab == adreseTP)
                {
                    adresaUC1.IdPartener = dr2.IDPartener;
                }

                if (tabControlPrincipal.SelectedTab == contacteTP)
                {
                    contactUC1.IdPartener = dr2.IDPartener;
                }
                
            }
        }

        private void tabPage1_Validating(object sender, CancelEventArgs e)
        {

            Boolean eEroare = false;
            if (CUIMTB.Text.Trim() == String.Empty)
            {
                //MessageBox.Show("Va rugam completati numarul documentului!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Error);
                errorProvider1.SetError(CUIMTB, "Va rugam completati CUI-ul partenerului!");
                eEroare = true;
            }
            else
                errorProvider1.SetError(CUIMTB, String.Empty);

            if (denumireTB.Text.Trim() == String.Empty)
            {
                //MessageBox.Show("Va rugam completati numarul documentului!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Error);
                errorProvider1.SetError(denumireTB, "Va rugam completati denumirea partenerului!");
                eEroare = true;
            }
            else
                errorProvider1.SetError(denumireTB, String.Empty);

            if (eEroare)
            {
                e.Cancel = true;
                return;
            }
        }

        private void DeleteError_Enter(object sender, EventArgs e)
        {
            errorProvider1.SetError((Control)sender, String.Empty);
        }

        private void nUMEComboBox_Validated(object sender, EventArgs e)
        {
            if (TariCB.Text == String.Empty)
                return;
            if (TariCB.SelectedIndex == -1)
            {

            }
            //String locInsert = iDLocalitateCB.Text.Trim();
            //searchPartenerBS.Filter = "Nume like '%" + iDLocalitateCB.Text.Trim() + "%'";
            //int nrLoc = searchPartenerBS.Count;
            //iDLocalitateCB.Text = locInsert;
            //if (nrLoc == 0)
            //{
            //    LocalitatiFrm frm = new LocalitatiFrm(ModuleInfo);
            //    frm.CodJudet = IdJudetSelectat;
            //    frm.LocalitateAdaugate = locInsert;
            //    frm.ShowDialog();

            //    SqlConnection con = DeschideConexiune(workConnString);
            //    localitatiTableAdapter.Connection = con;
            //    localitatiTableAdapter.FillByJudet(esrpDataSetParteneri.Localitati, IdJudetSelectat);
            //    InchideConexiune(con);

            //    localitatiBindingSource.Filter = "Nume like '%" + iDLocalitateCB.Text.Trim() + "%'";
            //    nrLoc = localitatiBindingSource.Count;
            //    localitatiBindingSource.Filter = String.Empty;
            //    iDLocalitateCB.Text = locInsert.Trim();
 
            //}
        }

        override public void Salvare(object sender, EventArgs args)
        {
            Cursor.Current = Cursors.WaitCursor;
            SqlConnection con = DeschideConexiune(workConnString);
            #region Validare Persoana de Contact
            String NumeDelegat = NumeDelegatCB.Text;
            //String PrenumeDelegat = PrenumeDelegatCB.Text;
            String SerieAI = SerieAICB.Text;
            String NumarAI = NumarAICB.Text;

            Boolean updateRec = false;

            if (NumeDelegatCB.Text.Trim() != String.Empty)
            {
                if (NumeDelegatCB.SelectedIndex == -1 /*|| PrenumeDelegatCB.SelectedIndex == -1*/)
                {
                    ///numele sau prenumele nu e acelasi cu cel din baza de date... il adaugam
                    ///
                    ESRPDataSetParteneri.ContactRow cr = ((DataRowView)fKContactParteneriBindingSource.AddNew()).Row as ESRPDataSetParteneri.ContactRow;
                    cr.Nume = NumeDelegat;
                    //cr.Prenume = PrenumeDelegat;
                    cr.SerieAI = SerieAI;
                    cr.NumarAI = Decimal.Zero;
                    if (NumarAI != String.Empty)
                        cr.NumarAI = Convert.ToDecimal(NumarAI);

                    cr.IDTipContact = 5; //delegat
                    updateRec = true;
                }
                else
                {
                    ESRPDataSetParteneri.ContactRow cr = ((DataRowView)fKContactParteneriBindingSource.Current).Row as ESRPDataSetParteneri.ContactRow;
                    if (SerieAICB.SelectedIndex == -1)
                    {
                        cr.SerieAI = SerieAI;
                        updateRec = true;
                    }
                    if (NumarAICB.SelectedIndex == -1)
                    {
                        cr.NumarAI = Convert.ToDecimal(NumarAI);
                        updateRec = true;
                    }

                }
                if (updateRec)
                {
                    fKContactParteneriBindingSource.EndEdit();
                    contactTableAdapter.Connection = con;
                    contactTableAdapter.Update(this.esrpDataSetParteneri.Contact);
                    this.contactTableAdapter.Fill(this.esrpDataSetParteneri.Contact);


                    NumeDelegatCB.Text = NumeDelegat;
                    //PrenumeDelegatCB.Text = PrenumeDelegat;
                    SerieAICB.Text = SerieAI;
                    NumarAICB.Text = NumarAI;
                }
            }
            #endregion

            #region Modificare Mijloc transport
            String NumeMT = NumeMTCB.Text;
            String NumarMT = NumarMTCB.Text;


            updateRec = false;
            if (NumarMTCB.Text.Trim() != String.Empty)
            {
                if (NumarMTCB.SelectedIndex == -1)
                {
                    ///numele MT nu e acelasi cu cel din baza de date... il adaugam
                    ///

                    ESRPDataSetParteneri.MijloaceTransportRow cr = ((DataRowView)fKMijloaceTransportParteneriBindingSource.AddNew()).Row as ESRPDataSetParteneri.MijloaceTransportRow;
                    cr.Denumire = NumeMT;
                    cr.NrInmatriculare = NumarMT;
                    updateRec = true;
                }
                else
                {
                    ESRPDataSetParteneri.MijloaceTransportRow cr = ((DataRowView)fKMijloaceTransportParteneriBindingSource.Current).Row as ESRPDataSetParteneri.MijloaceTransportRow;
                    if (NumeMTCB.SelectedIndex == -1)
                    {
                        cr.NrInmatriculare = NumarMT;
                        updateRec = true;
                    }

                }
                if (updateRec)
                {
                    fKMijloaceTransportParteneriBindingSource.EndEdit();
                    mijloaceTransportTableAdapter.Connection = con;
                    mijloaceTransportTableAdapter.Update(this.esrpDataSetParteneri.MijloaceTransport);
                    this.mijloaceTransportTableAdapter.Fill(this.esrpDataSetParteneri.MijloaceTransport);

                    NumeMTCB.Text = NumeMT;
                    NumarMTCB.Text = NumarMT;
                }
            }
            #endregion

            InchideConexiune(con);


            this.SuspendLayout();
            base.Salvare(this, args);
            ResumeLayout();


            if (EroareSalvare)
                return;

            if (parteneriBindingSource.Count == 0)
                parteneriBindingSource.Filter = String.Empty;
            Cursor.Current = Cursors.Default;
        }

		private void parteneriBindingSource_CurrentChanged(object sender, EventArgs e)
		{

		}

		//private void parteneriBindingSource_CurrentChanged(object sender, EventArgs e)
		//{
		//    if(parteneriBindingSource.Current==null)
		//        return;
		//    ESRPDataSetParteneri.ParteneriRow prtRow = ((DataRowView)parteneriBindingSource.Current).Row as ESRPDataSetParteneri.ParteneriRow;
		//    if (prtRow == null)
		//        return;
		//    if (Convert.ToInt32(iDLocalitateCB.SelectedValue) != prtRow.IDLocalitate)
		//        iDLocalitateCB.SelectedValue = prtRow.IDLocalitate;

		//}
       
    }
    [Serializable]
    public class TipPartenerSursa
    {
        public TipPartenerSursa(String nume, String _type)
        {
            _Name = nume;
            _Type = _type;
        }

        private String _Name = String.Empty;
        [System.ComponentModel.Bindable(true)]
        public String Name
        {
            get
            {
                return _Name;
            }
            set
            {
                _Name = value;
            }
        }
        private String _Type = "FC";
        [System.ComponentModel.Bindable(true)]
        public String Type
        {
            get
            {
                return _Type;
            }
            set
            {
                _Type = value;
            }
        }

    }
}
